<template>
	<view class="container">
		<Navigator2 :title="$t('device.changeRole')"></Navigator2>
		<view class="content">
			<aloys-tab ref="aloysTab" :tabs="tabs" @change="onTabChange" :currentTab="currentTabIndex"
				 activeColor="#0052D9" inactiveColor="#000000" underlineColor="#0052D9">
				<view v-for="(tab, index) in tabs" :key="index" :slot="`content${index}`" class="bot-content">
					<view class="bot-card" :class="{ 'bot-selected': Number(b.id) === selectedBotId }"
						v-for="b in tab.bots" :key="b.id" @click="selectbot(b.id, b.name, b.description, b.voiceId, b.voiceName)">
						<view class="bot-img">
							<image src="/static/changerole_robot.png" mode="aspectFit" />
						</view>
						<view class="bot-info">
							<view class="bot_name">{{b.name}}</view>
							<view class="bot_tag">{{b.description}}</view>
						</view>
					</view>
				</view>
			</aloys-tab>
		</view>
		<view class="bottom-button">
			<button class="complete-btn" @click="onComplete">{{ $t('device.complete') }}</button>
		</view>
	</view>
</template>

<script>
	import api from '@/js/api.js'
	import Navigator2 from '@/components/Navigator2.vue'
	import aloysTab from '@/components/aloys-tab/aloys-tab.vue'

	export default {
		data() {
			return {
				tabs: [],
				id: 0,
				accountId: '',
				platform: null,
				selectedBotId: null, // 当前选中的智能体ID
				selectedBotName: '', // 当前选中的智能体名称
				selectedBotDesc: '', // 当前选中的智能体描述
				currentTabIndex: 0 ,// 当前选中的tab索引
				
				voiceId: 0,
				voiceName: '',
				voiceIsClone: false,
				networkPriority: true
			}
		},
		onLoad(param) {
			console.log('页面参数:', param)
			if (param.id) {
				this.id = param.id
			}
			if (param.botId) {
				// 确保数据类型一致，转换为数字
				this.selectedBotId = Number(param.botId)
				console.log('初始化选中botId:', this.selectedBotId, '类型:', typeof this.selectedBotId)
			}
			if (param.accountId) {
				this.accountId = param.accountId
			}
			if (param.platform) {
				this.platform = param.platform
			}
			if (param.voiceId) {
				this.voiceId = param.voiceId
			}
			if (param.voiceName) {
				this.voiceName = param.voiceName
			}
			if (param.voiceIsClone) {
				this.voiceIsClone = param.voiceIsClone
			}
			if (param.networkPriority) {
				this.networkPriority = param.networkPriority
			}
		},
		mounted() {
			this.getBots()
		},
		methods: {
			onTabChange(index) {
				console.log('Tab切换:', index)
				this.currentTabIndex = index
			},
			getBots() {
				api.getBots(this.platform, this.accountId).then(res => {
					console.log('API返回的原始数据:', res)
					console.log('当前selectedBotId:', this.selectedBotId)

					let typeArr = [...new Set(res.map(v => v.tag))]
					let tabs = []
					let found = false
					let tabIndex = 0
					let botIndex = 0
					for (const [i, type] of typeArr.entries()) {
						const bots = res.filter(b => b.tag == type)
						const tab = {
							title: type,
							bots
						}
						tabs.push(tab)
						if (!found) {
							const idx = bots.findIndex(b => Number(b.id) === this.selectedBotId)
							console.log(`检查tab ${i} (${type}):`, bots.map(b => ({
								id: b.id,
								name: b.name,
								idType: typeof b.id
							})))
							if (idx !== -1) {
								tabIndex = i
								botIndex = idx
								found = true
								console.log(`找到匹配的bot: tabIndex=${tabIndex}, botIndex=${botIndex}`)
							}
						}
					}
					this.tabs = tabs
					this.currentTabIndex = tabIndex

					console.log('最终tabs数据:', this.tabs)
					console.log('找到选中bot:', {
						tabIndex,
						botIndex,
						selectedBotId: this.selectedBotId
					})

					// 延迟执行滚动，确保DOM已渲染
					this.$nextTick(() => {
						setTimeout(() => {
							this.scrollToSelectedBot(tabIndex, botIndex)
						}, 500)
					})
				})
			},
			onComplete() {
				// 返回上一页
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/device/devicesetting?id=${this.id}&botId=${this.selectedBotId}&botName=${this.selectedBotName}&botDesc=${this.selectedBotDesc}&voiceId=${this.voiceId}&voiceName=${this.voiceName}&voiceIsClone=${this.voiceIsClone}&networkPriority=${this.networkPriority}`
					})
				}, 300)
			},
			selectbot(botId, botName, botDesc, voiceId, voiceName) {
				this.selectedBotId = Number(botId)
				this.selectedBotName = botName
				this.selectedBotDesc = botDesc
				this.voiceId = Number(voiceId)
				this.voiceName = voiceName
				this.voiceIsClone = false
				console.log('选择bot:', this.selectedBotId)
			},
			scrollToSelectedBot(tabIndex, botIndex) {
				console.log('开始滚动到bot:', {
					tabIndex,
					botIndex
				})

				// 延迟执行，确保swiper已经切换到正确的tab
				setTimeout(() => {
					// 使用uni.createSelectorQuery获取当前tab中的bot元素
					const query = uni.createSelectorQuery().in(this)
					query.selectAll('.bot').boundingClientRect(rects => {
						if (rects && rects.length > 0) {
							console.log('找到bot元素数量:', rects.length)

							// 计算目标bot在当前tab中的索引
							let targetIndex = 0
							for (let i = 0; i < tabIndex; i++) {
								targetIndex += this.tabs[i].bots.length
							}
							targetIndex += botIndex

							console.log('目标bot索引:', targetIndex)

							if (rects[targetIndex]) {
								const targetRect = rects[targetIndex]
								console.log('目标bot位置:', targetRect)

								// 尝试调用aloys-tab的滚动方法
								if (this.$refs.aloysTab) {
									this.$refs.aloysTab.scrollToPosition(targetRect.top - 100)
								}
							}
						}
					}).exec()
				}, 800) // 增加延迟时间，确保tab切换完成
			}
		},
		components: {
			Navigator2,
			aloysTab
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #F0F2F5;
	}

	.content {
		height: calc(100% - 88rpx - 80rpx);
		padding-bottom: 150rpx; /* 为底部按钮留出空间 */
		box-sizing: border-box;
	}

	.bot-content {
		padding: 30rpx 30rpx 40rpx 30rpx;
	}

	.bot-card {
		background: #FFFFFF;
		border-radius: 16rpx;
		border: 2rpx solid transparent;
		padding: 32rpx;
		margin-bottom: 30rpx;
		box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.bot-img {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 71.6px;
			height: 71.6px;
			background-color: #F7F9FC;
			border-radius: 100px;
			margin-right: 16rpx;
			image {
				width: 80px;
				height: 80px;
			}
		}

		&.bot-selected {
			border: 2rpx solid #667eea;
			box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
			background: #F3F6FE;
		}
	}

	.bot-info {
		display: flex;
		flex-direction: column;
		flex: 1;
		min-width: 0;
	}

	.bot_name {
		font-size: 16px;
		font-weight: 600;
		color: #1F2937;
		margin-bottom: 16rpx;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
	}

	.bot_tag {
		font-size: 12px;
		color: #6B7280;
		line-height: 1.4;
		word-break: break-all;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		max-height: 2.8em;
	}

	.radio-img {
		width: 40rpx;
		height: 40rpx;
		margin-left: 32rpx;
		flex-shrink: 0;
	}

	// Tab栏样式优化
	::v-deep .aloys-tab-bar {
		display: flex;
		flex-direction: row;
		background: #fff;
		border-bottom: 2rpx solid #F0F0F0;
		margin-bottom: 0;
		padding: 0 0 0 0;
	}

	::v-deep .tab-item {
		flex: 1;
		text-align: center;
		font-size: 32rpx;
		color: #BFBFBF;
		padding: 32rpx 0 24rpx 0;
		border-bottom: 2rpx solid transparent;
		background: none;
		font-weight: 400;
		transition: color 0.2s, border-bottom 0.2s;
	}

	::v-deep .tab-item.active {
		font-size: 32rpx!important;
		font-weight: 600!important;
		color: #0052D9 !important;
		border-bottom: 4rpx solid #0052D9 !important;
		background: none;
	}

	.bottom-button {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 15px;
		background-color: #FFFFFF;
		box-sizing: border-box;

		.complete-btn {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 48px;
			background-color: #0256FF;
			border-radius: 8px;
			font-size: 32rpx;
			font-weight: 400;
			color: #FFFFFF;
			border: none;
			transition: all 0.2s ease;

			&:active {
				background-color: #0245E6;
				transform: scale(0.98);
			}
		}
	}
</style>